package com.online.controller;

import com.alibaba.fastjson.JSONObject;
import com.online.entity.*;
import com.online.service.*;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/paper")
public class PaperController {

    @Autowired
    PaperService paperService;

    @Autowired
    ExamService examService;

    @Autowired
    OptionService optionService;

    @Autowired
    BlankService blankService;

    @Autowired
    CEService ceService;

    @Autowired
    StudentService studentService;

    @Autowired
    StudentAnswerService studentAnswerService;

    @Autowired
    AnswerService answerService;

    @Autowired
    StudentClassService studentClassService;

    /**
     * 自动组卷并在页面上显示所有试题，0为选择题，1为填空题
     *
     * @param examId
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/addPaper", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String addPaper(@RequestParam("examId") Integer examId, HttpServletRequest httpServletRequest) {

        //查询题库是否有此id的题型，有则自动查询出来,否则进行自动组卷
        List<Paper> paperList = paperService.showPaperByExamId(examId);

        if (!paperList.isEmpty()) {
            System.out.println("题库中有此类题");

//            查询题库中的选择题原始id
            List<Integer> optionIdList = paperService.showAllQuestionId(examId, 0);

//            根据选择题的原始id查询选择题的内容
            List<Option> optionList = new ArrayList<>();

            for (Integer o : optionIdList) {
                optionList.add(optionService.showOptionById(o));
            }

//            查询题库中填空题原始id
            List<Integer> blankIdList = paperService.showAllQuestionId(examId, 1);

//            查询填空题内容
            List<Blank> blankList = new ArrayList<>();
            for (Integer b : blankIdList) {
                blankList.add(blankService.showBlankById(b));
            }

            httpServletRequest.setAttribute("optionList", optionList);
            httpServletRequest.setAttribute("blankList", blankList);
            return "teacher/paper_detail";

        } else {
            System.out.println("自动组卷");

            //        获取填空题,选择题数量
            Exam exam = examService.showAExam(examId);

//        获取选择题的数量和知识点
            exam.getOptionsNumber();
            exam.getOptionsKnowledge();

//        获取填空题的数量和知识点
            exam.getBlanksNumber();
            exam.getBlanksKnowledge();

//        随机查询满足知识点的选择题
            List<Option> optionList = optionService.showByRandom(exam.getOptionsNumber(), exam.getOptionsKnowledge());
            System.out.println(optionList.size());

//        随机查询满足知识点的填空题
            List<Blank> blankList = blankService.showBlanksRandom(exam.getBlanksKnowledge(), exam.getBlanksNumber());

            System.out.println("选择题");
            for (Option o : optionList) {
                System.out.println(o.getOptionId());
                System.out.println(o.getKnowledge());
                System.out.println(o.getOptionQuestion());
            }

            System.out.println("填空题");
            for (Blank b : blankList) {
                System.out.println(b.getBlankId());
                System.out.println(b.getBlankQuestion());
                System.out.println(b.getKnowledge());
            }


//        插入此次试卷的选择题
            for (int i = 0; i < optionList.size(); i++) {
                Paper paper = new Paper();
                paper.setExamId(examId);
                paper.setQuestionONumber(optionList.get(i).getOptionId());
                paper.setQuestionENumber(i + 1);
                paper.setQuestionType(0);
                int result = paperService.addARecordByExamId(paper);
            }

//        插入此次试卷的填空题
            for (int i = 0; i < blankList.size(); i++) {
                Paper paper = new Paper();
                paper.setQuestionType(1);
                paper.setExamId(examId);
                paper.setQuestionONumber(blankList.get(i).getBlankId());
                paper.setQuestionENumber(i + 1);
                int result = paperService.addARecordByExamId(paper);
            }

//            将题型自动组卷后展示在页面上
            httpServletRequest.setAttribute("optionList", optionList);
            httpServletRequest.setAttribute("blankList", blankList);
            return "teacher/paper_detail";
        }
    }

    /**
     * 查询学生的试卷内容
     *
     * @param examId
     * @param httpServletRequest
     * @return
     */
    @RequestMapping(value = "/showStudentPaper", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public synchronized String studentGoExam(@RequestParam("examId") String examId, HttpServletRequest httpServletRequest) {

        //查询题库是否有此id的题型，有则自动查询出来,否则进行自动组卷
        List<Paper> paperList = paperService.showPaperByExamId(Integer.parseInt(examId));

        if (paperList.isEmpty()) {

            System.out.println("自动组卷");

            //        获取填空题,选择题数量
            Exam exam = examService.showAExam(Integer.parseInt(examId));

//        获取选择题的数量和知识点
            exam.getOptionsNumber();
            exam.getOptionsKnowledge();

//        获取填空题的数量和知识点
            exam.getBlanksNumber();
            exam.getBlanksKnowledge();

//        随机查询满足知识点的选择题
            List<Option> optionList = optionService.showByRandom(exam.getOptionsNumber(), exam.getOptionsKnowledge());
            System.out.println(optionList.size());

//        随机查询满足知识点的填空题
            List<Blank> blankList = blankService.showBlanksRandom(exam.getBlanksKnowledge(), exam.getBlanksNumber());

            System.out.println("选择题");
            for (Option o : optionList) {
                System.out.println(o.getOptionId());
                System.out.println(o.getKnowledge());
                System.out.println(o.getOptionQuestion());
            }

            System.out.println("填空题");
            for (Blank b : blankList) {
                System.out.println(b.getBlankId());
                System.out.println(b.getBlankQuestion());
                System.out.println(b.getKnowledge());
            }


//        插入此次试卷的选择题
            for (int i = 0; i < optionList.size(); i++) {
                Paper paper = new Paper();
                paper.setExamId(Integer.parseInt(examId));
                paper.setQuestionONumber(optionList.get(i).getOptionId());
                paper.setQuestionENumber(i + 1);
                paper.setQuestionType(0);
                int result = paperService.addARecordByExamId(paper);
            }

//        插入此次试卷的填空题
            for (int i = 0; i < blankList.size(); i++) {
                Paper paper = new Paper();
                paper.setQuestionType(1);
                paper.setExamId(Integer.parseInt(examId));
                paper.setQuestionONumber(blankList.get(i).getBlankId());
                paper.setQuestionENumber(i + 1);
                int result = paperService.addARecordByExamId(paper);
            }

            //查询试卷中的题目的题库编号
            List<Integer> optionIdList = paperService.showAllQuestionId(Integer.parseInt(examId), 0);
            List<Integer> blankIdList = paperService.showAllQuestionId(Integer.parseInt(examId), 1);
            Option option = new Option();
            Blank blank = new Blank();

            List<Option> options = new ArrayList<>();
            List<Blank> blanks = new ArrayList<>();

            //查询试卷中每一道题的详细情况
            for (int i = 0; i < optionIdList.size(); i++) {
                option = optionService.showOptionById(optionIdList.get(i));
                options.add(option);
            }

            for (int i = 0; i < blankIdList.size(); i++) {
                blank = blankService.showBlankById(blankIdList.get(i));
                blanks.add(blank);
            }

            httpServletRequest.setAttribute("examId", examId);
            httpServletRequest.setAttribute("optionList", options);
            httpServletRequest.setAttribute("blankList", blanks);
            httpServletRequest.setAttribute("allPage", options.size() + blanks.size());
            return "student/student_paper_detail";

        } else {

            //查询试卷中的题目的题库编号
            List<Integer> optionIdList = paperService.showAllQuestionId(Integer.parseInt(examId), 0);
            List<Integer> blankIdList = paperService.showAllQuestionId(Integer.parseInt(examId), 1);
            Option option = new Option();
            Blank blank = new Blank();

            List<Option> optionList = new ArrayList<>();
            List<Blank> blankList = new ArrayList<>();

            //查询试卷中每一道题的详细情况
            for (int i = 0; i < optionIdList.size(); i++) {
                option = optionService.showOptionById(optionIdList.get(i));
                optionList.add(option);
            }

            for (int i = 0; i < blankIdList.size(); i++) {
                blank = blankService.showBlankById(blankIdList.get(i));
                blankList.add(blank);
            }

            httpServletRequest.setAttribute("examId", examId);
            httpServletRequest.setAttribute("optionList", optionList);
            httpServletRequest.setAttribute("blankList", blankList);
            httpServletRequest.setAttribute("allPage", optionList.size() + blankList.size());
            return "student/student_paper_detail";
        }
    }

    /**
     * 查询试卷的提交情况
     *
     * @param examId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/showHandleStu", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showHandleStu(@RequestParam(value = "examId", required = false) Integer examId) {
        //查询试卷的详情
        Exam exam = examService.showAExam(examId);

        //查询试卷的班级
        List<CEContact> ceContactList = ceService.showARecordByExamId(examId);

        //查询班级的总人数
        int count = 0;
        for (CEContact list : ceContactList) {
            List<Student> students = studentService.showByStudentClass(list.getClassName());
            count = count + students.size();
        }
        System.out.println(count);

        //查询此次考试已经提交完的人数
        List<StudentAnswer> list = studentAnswerService.countDeliver(examId);

        if (list.size() == 0) {
            ErrorJsonObject errorJsonObject = new ErrorJsonObject(105, "查询成功");
            return JSONObject.toJSONString(errorJsonObject);
        } else {
            CorrectJsonObject correctJsonObject = new CorrectJsonObject("查询成功");
            correctJsonObject.put("AllStudent", count);
            correctJsonObject.put("number", list.size());
            return JSONObject.toJSONString(correctJsonObject);
        }
    }

    /**
     * 查询一次测试的错误情况
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/showError", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String showError(HttpServletRequest request) {

        Integer examId = Integer.valueOf(request.getParameter("examId"));

        System.out.println("题库中有此类题");

        //存储一道题的答错的人数
        List<Integer> optionCorrect = new ArrayList<>();
        List<Integer> blankCorrect = new ArrayList<>();

//            查询题库中的选择题原始id
        List<Integer> optionIdList = paperService.showAllQuestionId(examId, 0);

//            根据选择题的原始id查询选择题的内容
        List<Option> optionList = new ArrayList<>();

        for (Integer o : optionIdList) {
            optionList.add(optionService.showOptionById(o));
        }

//            查询题库中填空题原始id
        List<Integer> blankIdList = paperService.showAllQuestionId(examId, 1);

//            查询填空题内容
        List<Blank> blankList = new ArrayList<>();
        for (Integer b : blankIdList) {
            blankList.add(blankService.showBlankById(b));
        }

// 遍历选择题原始id查询选择题的正确答案
        List<String> correctAnswerOfOptionList = new ArrayList<>();
        for (Integer o : optionIdList) {
            Answer answer = answerService.showAAnswer(0, o);
            correctAnswerOfOptionList.add(answer.getAnswerContent());
        }

//遍历填空题原始id查询填空题正确答案
        List<String> correctAnswerOfBlankList = new ArrayList<>();
        for (Integer o : blankIdList) {
            System.out.println(o);
            Answer answer = answerService.showAAnswer(1, o);
            System.out.println(answer.getAnswerContent());
            correctAnswerOfBlankList.add(answer.getAnswerContent());
        }

//        查询此试题已提交的学生的学号
        List<StudentAnswer> answerList = studentAnswerService.countDeliver(examId);

        //遍历所有的选择题
        for (int i = 0; i < correctAnswerOfOptionList.size(); i++) {
            int count = 0;
            //遍历做了此题的学生
            for (StudentAnswer list : answerList) {
                //得到每一个学生的学号
                String studentNumber = list.getStudentNumber();

                //根据学号查询学生的选择题答案
                List<StudentAnswer> answersOptions = studentAnswerService.showStudentOptionAnswer(studentNumber, examId);

                if (!answersOptions.get(i).getStudentAnswer().equals(correctAnswerOfOptionList.get(i))) {
                    count++;
                }
            }
            optionCorrect.add(count);
        }

        //遍历所有的填空题
        for (int i = 0; i < correctAnswerOfBlankList.size(); i++) {

            int count = 0;

            //遍历做了此题的学生
            for (StudentAnswer list : answerList) {

                //得到每一个学生的学号
                String studentNumber = list.getStudentNumber();

                //根据学号查询学生的选择题答案
                List<StudentAnswer> answersBlanks = studentAnswerService.showStudentBlankAnswer(studentNumber, examId);

                if (!answersBlanks.get(i).getStudentAnswer().equals(correctAnswerOfBlankList.get(i))) {
                    count++;
                }
            }
            blankCorrect.add(count);
        }

        request.setAttribute("optionCorrect", optionCorrect);
        request.setAttribute("blankCorrect", blankCorrect);
        request.setAttribute("optionAnswer", correctAnswerOfOptionList);
        request.setAttribute("blankAnswer", correctAnswerOfBlankList);
        request.setAttribute("optionList", optionList);
        request.setAttribute("blankList", blankList);
        return "teacher/student_error";
    }

    /**
     * 查询一次测试的试卷信息和班级信息
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/showPaperDetail", method = RequestMethod.GET, produces = "text/html")
    public String showPaperDetail(HttpServletRequest request) {

        //获取当前登录用户
        Subject subject = SecurityUtils.getSubject();
        String teacherNumber = String.valueOf(subject.getPrincipals());

        //获取试卷的id
        Integer examId = Integer.valueOf(request.getParameter("examId"));

        //根据试卷id查询试卷详情
        Exam exam = examService.showAExam(examId);

        //根据试卷id查询班级试卷关系
        List<CEContact> ceContact = ceService.showARecordByExamId(examId);

        //获取班级的名字
        List<String> classList = new ArrayList<>();
        for (CEContact ce : ceContact) {
            classList.add(ce.getClassName());
        }

        //根据班级名字和当前登录老师查询班级id
        List<Integer> idList = new ArrayList<>();
        for(String className : classList) {
            StudentClass studentClass = studentClassService.showAClass(teacherNumber,className);
            idList.add(studentClass.getClassId());
        }

        //根据班级名字查询班级id

        request.setAttribute("classId",idList);
        request.setAttribute("exam", exam);
        request.setAttribute("classList", classList);

        return "teacher/paperInfo";
    }

    /**
     * 导出一份试卷信息
     * @param
     * @param
     * @param
     * @return
     */
    @RequestMapping(value = "/exportPaper", method = RequestMethod.GET, produces = "text/html;charset=UTF-8")
    public String derivePaper(HttpServletRequest request) {

        Integer examId = Integer.valueOf(request.getParameter("examId"));
        Integer classId = Integer.valueOf(request.getParameter("classId"));

        //获取服务器路径
        String serverPath = request.getSession().getServletContext().getRealPath("/word/");

        //存储学生的试卷信息
        List<String> paperList = new ArrayList<>();

        //存储要写入的数据
        List<String> stringList = new ArrayList<>();

        //根据classId查询className
        StudentClass studentClass = studentClassService.showClassDetailById(classId);

        String className = studentClass.getClassName();

        //根据className查询该班级的所有学生
        List<Student> studentList = studentService.showByStudentClass(className);

        //查询此班级已提交的答案,存储在answerList中
        List<StudentAnswer> answerList = new ArrayList<>();

        for(Student student : studentList) {
            //查询一个学生的选择题答案
            List<StudentAnswer> studentAnswer = studentAnswerService.showStudentOptionAnswer(student.getStudentNumber(),examId);
            for(StudentAnswer answer : studentAnswer) {
                answerList.add(answer);
            }
        }

        //查询题库中的选择题原始id
        List<Integer> optionIdList = paperService.showAllQuestionId(examId, 0);

//            根据选择题的原始id查询选择题的内容
        List<Option> optionList = new ArrayList<>();

        for (Integer o : optionIdList) {
            optionList.add(optionService.showOptionById(o));
        }

        //            查询题库中填空题原始id
        List<Integer> blankIdList = paperService.showAllQuestionId(examId, 1);

//            查询填空题内容
        List<Blank> blankList = new ArrayList<>();
        for (Integer b : blankIdList) {
            blankList.add(blankService.showBlankById(b));
        }

        //遍历学生
        for (StudentAnswer studentAnswer : answerList) {

            //得到此学生关于选择题的答案
            List<StudentAnswer> optionAnswerList = studentAnswerService.showStudentOptionAnswer(studentAnswer.getStudentNumber(),examId);
            //查询此班级已提交的填空题的答案,存储在blankList中
            List<StudentAnswer> blankAnswerList = studentAnswerService.showStudentBlankAnswer(studentAnswer.getStudentNumber(),examId);
            stringList.add("一:单选题");

            for(int j = 0; j < optionList.size(); j++ ) {

                System.out.println("第" + (j+1) + "道");
                System.out.println(optionList.get(j).getOptionQuestion());
                System.out.println(optionList.get(j).getOptionA());
                System.out.println(optionList.get(j).getOptionB());
                System.out.println(optionList.get(j).getOptionC());
                System.out.println(optionList.get(j).getOptionD());
                System.out.println("学生答案:" + optionAnswerList.get(j).getStudentAnswer());

                stringList.add((j+1) +"、" + optionList.get(j).getOptionQuestion());
                stringList.add("(" + optionAnswerList.get(j).getStudentAnswer()+")");
                stringList.add("A:" + optionList.get(j).getOptionA());
                stringList.add("B:" +optionList.get(j).getOptionB());
                stringList.add("C:" +optionList.get(j).getOptionC());
                stringList.add("D:" +optionList.get(j).getOptionD());
            }
            optionAnswerList.clear();

            stringList.add("二:填空题");
            for(int j = 0; j < blankList.size(); j++) {
                stringList.add((j+1) + "、" + blankList.get(j).getBlankQuestion());
                stringList.add(blankAnswerList.get(j).getStudentAnswer());
            }

            blankAnswerList.clear();
            //将数据写入到文档
            try {

                //获取每一个学生的学号和姓名
                Student student = studentService.showByStudentNumber(studentAnswer.getStudentNumber());

                //获取试卷的名字
                Exam exam = examService.showAExam(examId);
                exam.getExamName();

                //word文件命名
                String wordName = className + student.getStudentNumber() + student.getStudentName() + exam.getExamName() + ".docx";

                //删除存在的文件
                File f = new File(serverPath + wordName);
                if(f.exists()) {
                    f.delete();
                }

                if(!paperList.contains(wordName)) {
                    paperList.add(wordName);
                }

                //创建一个word文档
                XWPFDocument xwpfDocument = new XWPFDocument();
                FileOutputStream fileOutputStream = new FileOutputStream(serverPath + wordName);

                for(int i = 0; i < stringList.size(); i++) {

                    //创建一个段落
                    XWPFParagraph paragraph = xwpfDocument.createParagraph();

                    //创建段落文本
                    XWPFRun xwpfRun = paragraph.createRun();
                    //向段落文本中写入数据
                    xwpfRun.setText(stringList.get(i));
                }
                xwpfDocument.write(fileOutputStream);
                fileOutputStream.close();
                stringList.clear();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        request.setAttribute("paperList",paperList);
        return "teacher/export_paper";
    }
}
